<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card style="margin-top:1%">
      <!--添加角色 -->
      <el-row>
        <el-button type="primary">添加角色</el-button>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolelist">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>

              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 渲染二级权限 -->
                  <el-col span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{ scope.row }}</pre> -->
          </template>
        </el-table-column>
        <!-- id -->
        <el-table-column type="index"></el-table-column>
        <!-- 角色名称 -->
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <!-- 角色描述 -->
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="small"
              >搜索</el-button
            >
            <el-button type="danger" icon="el-icon-delete" size="small"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="small"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="60%"
      @close = "setRightDialogClosed"
    >
          <!-- 树形结构 -->
      <el-tree :data="rightslist" :props="treeProps" show-checkbox node-key="id" default-expand-all = 'true' :default-checked-keys='defaultKeys' ref="treeRef"> </el-tree>    
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolelist: [],
      setRightDialogVisible:false,
      rightslist: [],
      treeProps:{
        label: 'authName',
        children: 'children'
      },
      defaultKeys:[],
      roleId: ''
    };
  },
  created() {
    // 在页面创造时，获取数据
    this.getRoleList();
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get("roles");
      //    请求失败
      if (res.meta.status !== 200) {
        return this.$message.error("请求失败！");
      }
      //   请求成功
      this.rolelist = res.data;
      console.log(this.rolelist);
    },
    async removeRightById(role, rightId) {
      // confirm请求成功是放回confirm,失败返回
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);

      if (confirmResult !== "confirm") {
        return this.$message.info("你取消了本次删除");
      }
      // 删除权限业务
      // 1.发起删除请求
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      // 2.判断删除是否成功r
      if (res.meta.status !== 200) {
        return this.$message.error("删除权限失败");
      }
      // 删除成功，重新对该角色赋值
      role.children = res.data;
    },
    // 当点击修改权限时，把对应的id传过来
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限数据
      const {data: res} =  await  this.$http.get('rights/tree')
      // 请求失败
      if(res.meta.status !== 200){
        return this.$message.error('获取用户权限失败！')
      }
      // 获取成功
      this.rightslist = res.data
      // 递归三级节点
      this.getLeftKeys(role , this.defaultKeys)
      this.setRightDialogVisible = true
    },
    getLeftKeys(node , arr){
      // 如果当前没有子节点，说明是三级节点，就把三级接点放到一个数组中
      if(!node.children){
        return arr.push(node.id)
      }
      // 递归三级节点id
      node.children.forEach(item => 
        this.getLeftKeys(item,arr)
        
      );
    },
    // 关闭对话框时，重置权限数组
    setRightDialogClosed(){
      this.defaultKeys = []
    },
    // 点击为角色分配权限
    async allotRights(){
      // 拿到选中的权限id
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
        // 拼接id
      const idStr  =  keys.join(',')
      // 发起数据请求
      const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{ rids : idStr})
      // 请求失败
      if(res.meta.status !== 200){
        return this.$message.error('权限请求失败！')
      }
      // 请求成功
      this.$message.success('请求权限成功！')
      // 重新请求权限列表
      this.getRoleList()
      // 隐藏弹窗
      this.setRightDialogVisible = false



    }
  }
};
</script>

<style>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eeeeee;
}

.bdbottom {
  border-bottom: 1px solid #eeeeee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>